package cn.uniquesoft.api;

import cn.uniquesoft.service.*;
import cn.uniquesoft.util.*;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.CodeVO;
import cn.uniquesoft.vo.RoleVO;
import cn.uniquesoft.vo.UserVO;
import com.aliyuncs.dysmsapi.model.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping(value = "/api/login")
public class ApiLoginController {
    @Autowired
    private ILogService logSerivce;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IBankService bankService;
    @Autowired
    private ICodeService codeService;

    @Value("${jstx.url}")
    private String jstxUrl;
    @Value("${jstx.orgname}")
    private String jstxOrgName;
    @Value("${jstx.appname}")
    private String jstxAppName;


    @RequestMapping(value = "/toRegist")
    @ResponseBody
    public AnswerVO toRegist(int iusertype, String loginname, String password, String cphone, String code, String cunit, int iorgname) {
        AnswerVO answerVO = new AnswerVO();
        // 验证当前验证码是否正确，是否超时，是否是当前手机应受到的验证码
        CodeVO customerVO = this.codeService.findItemByCphone(cphone);// 通过手机号获取已经发送的验证码信息，及验证码的有效时间等信息来登录
        //判断验证码是否正确，忽略大小写
        if (!customerVO.getCcode().equalsIgnoreCase(code)) {
            answerVO.setMsg("验证码不正确，请重新输入或获取！");
            answerVO.setSuccess(false);
            return answerVO;
        }
        //验证码通过，判断验证码是否在有效期内，默认时长为10分钟
        Date date = new Date();
        if ((((int) date.getTime() - (int) customerVO.getDtime().getTime()) / 600000) > 10) {
            answerVO.setMsg("验证码超时，请重新获取验证码！");
            answerVO.setSuccess(false);
            return answerVO;
        }
        UserVO oldUserVO = this.userService.getUserByName(loginname);
        UserVO item = new UserVO();
        if (oldUserVO == null) {
            String csalt = SaltUtil.random4Number();
            String cloginpwd = Md5Util.md5(password);
            item.setCpassword(Md5Util.md5pwd(cloginpwd, csalt));
            item.setCsalt(csalt);
            item.setCname(loginname);
            item.setIusertype(iusertype);
            item.setCmobile(cphone);
            item.setCtype("1");
            item.setIspassed(2);
            item.setCstatus("0");
            item.setCunit(cunit);
            item.setIorgname(iorgname);
            if (iusertype == 2) {
                item.setCorgname(this.bankService.findOneById(iorgname).getCname());
            } else {
                item.setCorgname(this.companyService.findOneById(iorgname).getCname());
            }
            int i = this.userService.save(item);
            if (i > 0) {
                String param = "{\"username\":\"" + item.getCname() + "\",\"password\":\"" + item.getCname() + "\",\"nickname\":\"" + item.getCname() + "\"}";
                String msg = HttpUtil.doHttpsPostJson(jstxUrl + jstxOrgName + "/" + jstxAppName + "/users", param);
                if (null != msg && msg.length() > 0) {
                    answerVO.setSuccess(true);
                    answerVO.setMsg("注册成功，审核通过后可以登录！");
                } else {
                    answerVO.setSuccess(false);
                    answerVO.setMsg("注册失败,即时通信注册失败!");
                    this.userService.remove(item);
                }
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("注册失败！请联系管理员");
            }
        } else {
            answerVO.setSuccess(false);
            answerVO.setMsg("该账号已存在！");
        }
        return answerVO;
    }


    @RequestMapping(value = "/toLogin")
    @ResponseBody
    public AnswerVO toLogin(String loginname, String password) {
        AnswerVO answerVO = new AnswerVO();
        password = Md5Util.md5(password);
        UserVO userVO = this.userService.getUserByName(loginname);
        if (userVO == null) {
            answerVO.setMsg("账号不存在");
            answerVO.setSuccess(false);
            return answerVO;
        }
        if (!userVO.getCpassword().equals(Md5Util.md5(password + userVO.getCsalt()))) {
            answerVO.setMsg("密码错误");
            answerVO.setSuccess(false);
            return answerVO;
        }
        if (userVO.getIspassed() == 2) {
            answerVO.setMsg("用户正在审核中，请稍后尝试登陆");
            answerVO.setSuccess(false);
            return answerVO;
        }
        answerVO.setSuccess(true);
        answerVO.setMsg("用户登陆验证成功！");
        answerVO.setUser(userVO);
        return answerVO;
    }


    @RequestMapping(value = "/getOrgItems")
    @ResponseBody
    public AnswerVO getOrgItems(int itype) {
        AnswerVO answerVO = new AnswerVO();
        if (itype == 2) {
            answerVO.setData(this.bankService.findAll(null));
        } else {
            answerVO.setData(this.companyService.findAll(null));
        }
        return answerVO;
    }

    @RequestMapping(value = "/getCode")
    @ResponseBody
    public AnswerVO getCode(String cphone, HttpServletRequest request) {
        AnswerVO answerVO = new AnswerVO();
        answerVO.setSuccess(false);
        answerVO.setMsg("发送失败！");
        // 调用发送验证码的组件，调用阿里云短信服务发送验证码
        String ccode = AuthenticationUtil.authCode();
        try {
            // 更新code表信息，如果新的手机号，则插入，老手机号则更新
            CodeVO codeVO = this.codeService.findItemByCphone(cphone);// 通过手机号获取已经发送的验证码信息，及验证码的有效时间等信息来登录
            if (null == codeVO) {  // 用户不存在
                codeVO = new CodeVO();
                codeVO.setCphone(cphone);
                codeVO.setCcode(ccode);
                codeVO.setDtime(new Date());
                this.codeService.save(codeVO);
            } else {
                codeVO.setCcode(ccode);
                codeVO.setDtime(new Date());
                this.codeService.editCodeByCphone(codeVO);
            }
            answerVO = this.sendPhoneCode(cphone, ccode, answerVO);
            //           this.wxUserLoginService.editCodeByCphone(customerVO);
            // 成功发送验证码之后，更新该账号下
            answerVO.setSuccess(true);
            answerVO.setMsg("发送成功！");
//        } catch (ClientException e) {
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("发送失败！");
            e.printStackTrace();
        }
        return answerVO;
    }

    // 发送手机验证码
    public AnswerVO sendPhoneCode(String cname, String ccode, AnswerVO answerVO) throws ClientException {
        //调用短信接口发送短信,已测试成功，现注释
        SendSmsResponse sendSmsResponse = SmsSendUtil.sendSms(cname, ccode);
        if (sendSmsResponse.getCode().equalsIgnoreCase("OK")) {
            answerVO.setSuccess(true);
            answerVO.setMsg("验证码已发送");
        }
        return answerVO;
    }


    @RequestMapping(value = "/updatepwd")
    @ResponseBody
    public AnswerVO updatepwd(int iid, String oldpwd, String newpwd, HttpServletRequest request) {
        AnswerVO answerVO = new AnswerVO();
        UserVO userVO = this.userService.findOneById(iid);
        String cloginpwd = Md5Util.md5(oldpwd);
        cloginpwd = Md5Util.md5pwd(cloginpwd, userVO.getCsalt());
        if (!cloginpwd.equals(userVO.getCpassword())) {
            answerVO.setSuccess(false);
            answerVO.setMsg("原密码输入错误！");
            return answerVO;
        }
        cloginpwd = Md5Util.md5(newpwd);
        cloginpwd = Md5Util.md5pwd(cloginpwd, userVO.getCsalt());
        userVO.setCpassword(cloginpwd);
        int i = this.userService.resetPwd(userVO);
        if (i > 0) {

            answerVO.setSuccess(true);

            answerVO.setMsg("修改密码成功!");
        } else {
            answerVO.setSuccess(false);
            answerVO.setMsg("修改密码失败!");
        }
        return answerVO;
    }

}
